public class shuzhijisuan {
        public static void main(String[] args) {
            // 测试数组
            int[] arr1 = {1, -2, 3, 5, -1};
            int[] arr2 = {1, -2, 3, -8, 5, 1};
            int[] arr3 = {1, -2, 3, -2, 5, 1};
    
            // 输出结果
            System.out.println("最大子数组和: " + maxSum(arr1)); 
            System.out.println("最大子数组和: " + maxSum(arr2));
            System.out.println("最大子数组和: " + maxSum(arr3));
        }
    
        public static int maxSum(int[] nums) {
            if (nums == null || nums.length == 0) {
                throw new IllegalArgumentException("数组不能为空");
            }
    
            int maxSum = nums[0]; // 初始化最大子数组和为第一个元素
            int currentSum = nums[0]; // 初始化当前子数组和为第一个元素
    
            // 从数组的第二个元素开始遍历
            for (int i=1; i<nums.length; i++) {
                // 更新当前子数组和
                currentSum = Math.max(nums[i],currentSum+nums[i]);
                // 更新最大子数组和
                maxSum = Math.max(maxSum,currentSum);
            }
    
            return maxSum;
        }
    }

